<template>
  <div class="pager" v-if="total > 0">
    <a
      href=""
      class="pager-item"
      :class="{ disabled: pageNo === 1 }"
      @click.prevent="handleChange(1)"
      >首页</a
    >
    <a
      href=""
      class="pager-item"
      :class="{ disabled: pageNo === 1 }"
      @click.prevent="handleChange(pageNo - 1)"
      >上一页</a
    >
    <a
      href=""
      class="pager-item"
      :class="{ active: i === pageNo }"
      @click.prevent="handleChange(i)"
      v-for="i in panelNums"
      :key="i"
      >{{ i }}</a
    >
    <a
      href=""
      class="pager-item"
      :class="{ disabled: pageNo === totalPage }"
      @click.prevent="handleChange(pageNo + 1)"
      >下一页</a
    >
    <a
      href=""
      class="pager-item"
      :class="{ disabled: pageNo === totalPage }"
      @click.prevent="handleChange(totalPage)"
      >最后一页</a
    >

    <span class="pager-text">
      <i>{{ pageNo }}</i> /
      <i>{{ totalPage }}</i>
    </span>
  </div>
</template>

<script>
export default {
  props: {
    // 当前页码
    pageNo: {
      default: 1,
      type: Number
    },
    // 总条数
    total: {
      default: 0,
      type: Number
    },
    // 每页显示条数
    pageSize: {
      default: 10,
      type: Number
    },
    // 最多显示页码数
    panelSize: {
      default: 10,
      type: Number
    }
  },
  computed: {
    // 总页数
    totalPage () {
      return Math.ceil(this.total / this.pageSize)
    },
    minNum () {
      // 计算当前显示的最小页码数字
      var min = Math.floor(this.pageNo - this.panelSize / 2) + 1
      if (min > this.totalPage - this.panelSize + 1) {
        min = this.totalPage - this.panelSize + 1
      }
      if (min < 1) {
        min = 1
      }
      return min
    },
    maxNum () {
      // 计算当前显示的最大页码数字
      var max = this.minNum + this.panelSize - 1
      if (max > this.totalPage) {
        max = this.totalPage
      }
      return max
    },
    panelNums () {
      var nums = []
      for (let i = this.minNum; i <= this.maxNum; i++) {
        nums.push(i)
      }
      return nums
    }
  },
  methods: {
    handleChange (pageNo) {
      if (pageNo < 1) {
        pageNo = 1
      } else if (pageNo > this.totalPage) {
        pageNo = this.totalPage
      } else if (pageNo === this.pageNo) {
        // 页码没有变化
        return
      }
      this.$emit('pageChange', pageNo)
    }
  }
}
</script>

<style lang="scss" scoped>
.pager {
  text-align: center;
  margin: 20px 0;
  .pager-item {
    display: inline-block;
    padding: 5px 7px;
    border: 1px solid #ccc;
    margin: 8px;
    cursor: pointer;
    color: #6060e0;
    &.disabled {
      color: #ccc;
      cursor: not-allowed;
    }
    &.active {
      color: #f40;
      border: none;
      cursor: auto;
    }
  }
}
</style>
